package com.zhiyou.controller;

import com.sun.deploy.association.RegisterFailedException;
import com.zhiyou.entity.User;
import com.zhiyou.ex.OperationException;
import com.zhiyou.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import com.zhiyou.entity.User;
import com.zhiyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping(value = "/getAll")
    public void getAll(){
        List<User> all = userService.getAll();
        System.out.println("all = " + all);
    }

    //登录
    @RequestMapping("/login")
    public String login(User user, HttpSession session) throws Exception{
        //获取当前对象
        Subject current = SecurityUtils.getSubject();
        if(!current.isAuthenticated()){//未认证，即还没有登录或者登录过期了
            //前端传来的用户名和密码放入UsernamePasswordToken中
            System.out.println(user.getuUsername()+","+user.getuPassword());
            UsernamePasswordToken token = new UsernamePasswordToken(user.getuUsername(), user.getuPassword());
            //剩下的交给shiro
            try {
                current.login(token);
            }catch (Exception e){
//              throw  new OperationException("用户名或或者密码错误");
            }

        }
//        User login = userService.login(user);
//        if (login==null){
//            return "redirect:/login.html";
//        }
//        session.setAttribute("user",login);
        return "forward:/index2.html";
    }

    //登出
    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/login.jsp";
    }

    @RequestMapping("/regist")
    public String register(User user){
        try {
            userService.register(user);
            System.out.println("注册成功");
        }
        catch (Exception e) {
            System.out.println("注册失败");
            return "redirect:/regist.jsp";
        }

        return "redirect:/login.jsp";
    }
}
